//
//  PKRequestManager.m
//  PianKe
//
//  Created by mingtao on 15/9/26.
//  Copyright (c) 2015年 mingtao. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager


+(void) requestWithType:(RequestType *)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinsh) finish error:(RequestError)error
{
    PKRequestManager *manage=[[PKRequestManager alloc]init];
    
    [manage requestWithType:type urlString:urlString parDic:parDic finish:finish error:error];

}


-(void) requestWithType:(RequestType *)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinsh) finish error:(RequestError)error
{
    NSURL *url = [NSURL URLWithString:urlString];
    //创建可变的urlrequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //如果请求方式是POST需要设置参数和请求方式
    if (type == POST) {
        //设置请求方式
        [request setHTTPMethod:@"POST"];
        
        if (parDic.count>0) {
            
            NSData *data=[self parDicToDataWithDic:parDic];
            //设置请求参数的Body体
            [request setHTTPBody:data];
        }
    }
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data) {
            
            finish(data);
            
        }else
        {
            error(connectionError);
        
        }
        
    }];


}

//把字典转换为post请求所需要的参数体
-(NSData *)parDicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array=[NSMutableArray array];
    //遍历字典的到每一个键，得到所有的 key=value类型的字符串
    for (NSString *key in dic) {
        NSString *str=[NSString stringWithFormat:@"%@=%@",key,dic[key]];
        
        [array addObject:str];
    }
    //数组里所有Key = value的字符串通过&符号连接
  NSString *parString = [array componentsJoinedByString:@"&"];
    
    return [parString dataUsingEncoding:NSUTF8StringEncoding];
    
}


@end
